package com.weichai.app.arch.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.fragment.NavHostFragment;


import com.weichai.app.App;
import com.weichai.app.BR;
import com.weichai.app.R;
import com.weichai.app.arch.config.RouterParams;
import com.weichai.app.page.common.dialog.AlertDialog;

import dev.utils.app.toast.ToastUtils;
import dev.utils.common.ClassUtils;


/**
 * @ClassName: BaseFragment
 * @Description: Fragment 基类
 * @Author: 祖安
 * @Date: 2021/7/28 10:10 上午
 */
public abstract class BaseFragment<VB extends ViewDataBinding, VM extends BaseViewModel> extends Fragment {
    protected VB mViewBinding;
    protected VM mViewModel;
    protected AppCompatActivity mActivity;//依赖Activity
    private ProgressDialog mLoadingDialog;
    private boolean isLoaded = false;
    private final String TAG = "BaseFragment";

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = (AppCompatActivity) context;
        Log.e(TAG, "onAttach: " + getClass().getName());
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "onCreate: " + getClass().getName());
        mViewModel = initViewModel();
        initData();

    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.e(TAG, "onCreateView: " + getClass().getName());
        mViewBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
        mViewBinding.setLifecycleOwner(this);
        return mViewBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (mViewModel != null) {
            //DataBinding绑定数据
            mViewBinding.setVariable(BR.vm, mViewModel);
        }
        initView();
        //防止多次订阅
        if (!isLoaded) {
            initObserver();
            isLoaded = true;
        }
    }

    /**
     * 初始化视图
     */
    protected abstract void initView();

    /**
     * 初始化相关订阅
     */
    protected void initObserver() {
        if (mViewModel != null) {
            //页面跳跳转
            mViewModel.navigationData.observe(this, this::navigate);
            //加载进度弹窗
            mViewModel.showLoadingData.observe(this, value -> {
                if (mLoadingDialog == null) {
                    mLoadingDialog = new ProgressDialog(mActivity);
                }
                if (value) {
                    if (!mLoadingDialog.isShowing()) {
                        mLoadingDialog.show();
                    }
                } else {
                    if (mLoadingDialog.isShowing()) {
                        mLoadingDialog.dismiss();
                    }
                }
            });
            //展示吐司
            mViewModel.toastData.observe(this, value -> {
                ToastUtils.showLong(mActivity, value);
            });
            //返回上一级
            mViewModel.navigationPopData.observe(this, value -> {
                if (value == -1) {
                    popPage();
                } else {
                    popHome();
                }
            });

            mViewModel.alertData.observe(this, value -> {
                new AlertDialog(getContext())
                        .showAlert(value);
            });
        }

    }

    /**
     * 初始化数据
     */
    protected abstract void initData();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e(TAG, "onDestroyView: " + getClass().getName());

        if (mViewBinding != null) {
            mViewBinding.unbind();
            mViewBinding = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: " + getClass().getName());

        mActivity = null;
    }

    /**
     * 跳转页面 (Fragment)
     *
     * @param router 跳转参数
     */
    public void navigate(RouterParams router) {
        NavHostFragment.findNavController(this).navigate(router.pageID, router.params);
    }

    /**
     *
     */
    public void popPage() {
        NavHostFragment.findNavController(this).popBackStack();
    }

    /**
     * 返回主页
     */
    public void popHome() {
        NavHostFragment.findNavController(this).popBackStack(R.id.main_page, false);
    }

    /**
     * 初始化ViewModel
     * 默认加载无参构造方法
     *
     * @return
     */
    protected VM initViewModel() {
        Class<VM> vmClass = (Class<VM>) ClassUtils.getGenericSuperclass(this, 1);
        return getViewModel(vmClass);
    }

    /**
     * 获取布局ID
     *
     * @return ID
     */
    public abstract int getLayoutId();


    /**
     * 获取 Fragment ViewModel
     *
     * @param clz Model 类
     * @return ViewModel
     */
    public <T extends ViewModel> T getViewModel(Class<T> clz) {
        return new ViewModelProvider(this).get(clz);
    }

    /**
     * 获取 Activity ViewModel
     *
     * @param clz Model 类
     * @return ViewModel
     */
    public <T extends ViewModel> T getViewModelOfActivity(Class<T> clz) {
        return new ViewModelProvider(mActivity).get(clz);
    }

    /**
     * 获取 Application ViewModel
     *
     * @param clz Model 类
     * @return ViewModel
     */
    public <T extends ViewModel> T getViewModelOfApp(Class<T> clz) {
        return new ViewModelProvider(App.getApp()).get(clz);
    }

}
